import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Res,
  Req,
} from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto, LoginUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { PasswordPipe } from 'src/pipe/password.pipe';
import { Request, Response } from 'express';
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post()
  create(@Body(new PasswordPipe()) createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto);
  }
  @Get()
  findAll() {
    return this.userService.findAll();
  }
  @Get('/code')
  code(
    @Req() request: Request,
    @Res({ passthrough: true }) response: Response,
  ) {
    const captcha = this.userService.getCode();
    response.cookie('captcha', captcha.text, {
      httpOnly: true,
      maxAge: 20 * 1000,
    }); // 设置 Cookie
    return captcha.data;
  }
  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.userService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.userService.update(+id, updateUserDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.userService.remove(+id);
  }
  @Post('/login')
  login(@Body() createUserDto: LoginUserDto, @Req() request: Request) {
    const captcha = request.cookies['captcha'];
    return this.userService.login({ ...createUserDto }, captcha);
  }
}
